package com.star.common.kit.ip;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * ip -地区 缓存
 *
 * 周恒哲
 */
@Slf4j
public class Ip2RegionUtil {

    public static final String UNKNOWN_REGION = "未知地区";

    /**
     * ip 查找器
     */
    private static Searcher searcher;

    static {
        String path = "";
        try {
            File file = ResourceUtils.getFile("classpath:ip/ip2region.xdb");
            path = file.getAbsolutePath();
        } catch (Exception e) {
            log.error("文件不存在");
        }

        byte[] cBuff = null;
        try {
            cBuff = Searcher.loadContentFromFile(path);
        } catch (Exception e) {
            log.info("failed to load content from `{}`", path, e);
        }
        // 2、使用上述的 cBuff 创建一个完全基于内存的查询对象。
        try {
            searcher = Searcher.newWithBuffer(cBuff);
        } catch (Exception e) {
            log.error("failed to create content cached searcher: ", e);
        }
    }

    /**
     * ip-地区(省级别)
     *
     * @param ip
     * @return
     */
    public static String ip2region(String ip) {
        String s = UNKNOWN_REGION;
        try {
            long sTime = System.nanoTime();
            String region = searcher.search(ip);
            String[] split = region.split("\\|");
            if (split.length == 5) {
                if ("0".equalsIgnoreCase(split[2])) {
                    return s;
                }
                s = split[2].replace("省", "");
            }
            log.debug("{region: {}, ioCount: {}, took: {} μs}",
                    region,
                    searcher.getIOCount(),
                    TimeUnit.NANOSECONDS.toMicros((System.nanoTime() - sTime)));
        } catch (Exception e) {
            log.error("failed to search({})", ip, e);
        }
        return s;
    }

    /**
     * ip-国家
     *
     * @param ip
     * @return
     */
    public static String ip2country(String ip) {
        String s = UNKNOWN_REGION;
        try {
            long sTime = System.nanoTime();
            String region = searcher.search(ip);
            String[] split = region.split("\\|");
            if (split.length == 5) {
                s = split[0];
            }
            log.debug("{region: {}, ioCount: {}, took: {} μs}",
                    region,
                    searcher.getIOCount(),
                    TimeUnit.NANOSECONDS.toMicros((System.nanoTime() - sTime)));
        } catch (Exception e) {
            log.error("failed to search({}): ", ip, e);
        }
        return s;
    }

    /**
     * ip-国家
     *
     * @param ip
     * @return
     */
    public static String ip2city(String ip) {
        String s = UNKNOWN_REGION;
        try {
            long sTime = System.nanoTime();
            String region = searcher.search(ip);
            String[] split = region.split("\\|");
            if (split.length == 5) {
                s = split[3];
            }
            log.debug("{region: {}, ioCount: {}, took: {} μs}",
                    region,
                    searcher.getIOCount(),
                    TimeUnit.NANOSECONDS.toMicros((System.nanoTime() - sTime)));
        } catch (Exception e) {
            log.error("failed to search({}): ", ip, e);
        }
        return s;
    }


    /**
     * 详细地区信息
     * index 0-省 1-市
     *
     * @param ip
     * @return
     */
    public static Set<String> ip2regionInfo(String ip) {
        Set<String> regionSet = new HashSet<>(2);
        try {
            long sTime = System.nanoTime();
            String region = searcher.search(ip);
            if (StringUtils.isNotBlank(region)) {
                String[] split = region.split("\\|");
                int length = split.length;
                if (length > 3) {
                    //省
                    String province = split[2];
                    regionSet.add(province.replace("省", ""));
                }
                if (length > 4) {
                    //市
                    String city = split[3];
                    regionSet.add(city.replace("市", ""));
                }
            }
            log.debug("{region: {}, ioCount: {}, took: {} μs}",
                    region,
                    searcher.getIOCount(),
                    TimeUnit.NANOSECONDS.toMicros((System.nanoTime() - sTime)));
        } catch (Exception e) {
            log.error("failed to search({}): ", ip, e);
        }
        return regionSet;
    }


    private Ip2RegionUtil() {

    }
}
